package com.keensense.vcm.internal;

import static com.keensense.vcm.common.parser.ResponseParsers.loginResponseParser;
import static com.keensense.vcm.internal.VCMResourcePathConstants.LOGIN;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

import com.keensense.vcm.HttpMethod;
import com.keensense.vcm.common.auth.Credentials;
import com.keensense.vcm.common.auth.CredentialsProvider;
import com.keensense.vcm.common.comm.RequestMessage;
import com.keensense.vcm.common.comm.ServiceClient;
import com.keensense.vcm.model.VCMResponse;

/**
 * @author lanjian
 * @date 2020/4/30 11:40 上午
 */
public class LoginOperation extends VCMOperation {

    public LoginOperation(ServiceClient client, CredentialsProvider credsProvider) {
        super(client, credsProvider);
    }

    public VCMResponse login() {
        Credentials credentials = credentialsProvider.getCredentials();
        String userName = credentials.getUserName();
        String password = credentials.getPassword();
        Map<String, String> parameters = new HashMap<>(2);
        parameters.put("account", userName);
        parameters.put("pwd", password);
        RequestMessage request =
            new VCMRequestMessageBuilder(getInnerClient()).setEndpoint(endpoint).setMethod(HttpMethod.POST)
                .setParameters(parameters).setInputStream(new ByteArrayInputStream("{}".getBytes())).build();
        request.setResourcePath(LOGIN);
        VCMResponse response = doOperation(request, loginResponseParser, true);
        String cookies = response.getResult().getHeader();
        if (cookies != null && cookies.length() != 0) {
            String[] cookiesArray = cookies.split(";");
            credentials.setCookie(cookiesArray[0]);
        }
        credentialsProvider.setCredentials(credentials);
        return response;
    }

}
